package com.archgeek.java.filechannel;

import java.io.BufferedWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author pizhihui
 * @date 2023-04-03 15:04
 */
public class FileReadTest {

    public static void main(String[] args) throws Exception {
        // 生成测试文件
        generateTestFile();

        String filename = "test.txt";
        long startTime, endTime, timeElapsed;

        System.out.println("写文件结束............");

        // 使用 FileChannel 读取文件

        startTime = System.nanoTime();
        try (RandomAccessFile file = new RandomAccessFile(filename, "r")) {
            FileChannel channel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (channel.read(buffer) > 0) {
                buffer.flip();
                buffer.clear();
            }
        }
        endTime = System.nanoTime();
        timeElapsed = endTime - startTime;
        System.out.println("FileChannel: " + timeElapsed / 1000000 + "ms");

        // 使用 mmap 读取文件
        startTime = System.nanoTime();
        try (RandomAccessFile file = new RandomAccessFile(filename, "r")) {
            FileChannel channel = file.getChannel();
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            byte[] bytes = new byte[(int) channel.size()];
            buffer.get(bytes);
        }
        endTime = System.nanoTime();
        timeElapsed = endTime - startTime;
        System.out.println("mmap: " + timeElapsed / 1000000 + "ms");
    }

    private static void generateTestFile() throws Exception {
        Path path = Paths.get("test.txt");
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (int i = 0; i < 10000000; i++) {
                writer.write("Hello, world!\n");
            }
        }
    }


}
